#include "MainWindow.h"
#include "CopyPointer.h"
#include <string>
#include <iostream>
using namespace std;

MainWindow :: MainWindow(QWidget *parent) : QMainWindow(parent), LVM(new LeonardVirtualMachine()) {
	addMenu();
	doc = new Document(this);
	scrollDocument = new QScrollArea(this);
	scrollDocument->setWidget(doc);
	scrollDocument->setWidgetResizable(true);
	setCentralWidget(scrollDocument);
	connect(doc, SIGNAL(evaluateText(const QString&, int)), this, SLOT(inputTextMainWindow(const QString&, int)));
	connect(this, SIGNAL(outputTextMainWindow(const QString&, int)), doc, SLOT(outputText(const QString&, int)));
}

void MainWindow :: addMenu() {
	QAction *quit = new QAction(tr(EXITMENU), this);
	QMenu *fileMenu = menuBar()->addMenu(tr(FILEMENU));
	fileMenu->addAction(quit);
	connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow :: inputTextMainWindow(const QString& text, int code) {
	Character<> end(0);
	Character<> space(' ');
	ASSIGN(skip, (end));
	QString output("");
	QString textParse = text;
	QString tmp = textParse.replace(QString('\n'), QString(' '), Qt::CaseInsensitive);
	ParseStream *to_parse = new ParseStream(tmp.toStdString().c_str());
	ParseResult* check= new ParseResult;
	LeonardParser *LPs = new LeonardParser();
	GrammarDescriptor *td = new GrammarDescriptor(LPs);
	check = LPs->parse(to_parse, *td->getRoot(), skip);
	if ( check->result ) {
		LPs->top()->execute(LVM);
		output.append(LVM->evalTop()->toString().c_str());
		emit outputTextMainWindow(output, code);
		output.append("<br>");
	}
	else {
		output.append("!!! Invalid input !!!");
		emit outputTextMainWindow(output, code);
		output.append("<br>");
	}
}
